package com.chuanzhi.recyclingmalladmin.controller;


import com.chuanzhi.recyclingmall.common.result.Result;
import com.chuanzhi.recyclingmall.common.utils.IdentifyCode;
import com.chuanzhi.recyclingmalladmin.po.User;
import com.chuanzhi.recyclingmalladmin.service.UserLoginService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserLoginService userLoginService;


//    登录 账号:root 密码:123456
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result userLogin(@RequestBody User user){
        return userLoginService.getUserLogin(user);
    }
//  退出
    @GetMapping("/logout")
    @ApiOperation("用户退出登录(携带token)")
    public Result userLogout(){
        return userLoginService.userLogout();
    }

    @PutMapping("/register")
    @ApiOperation("用户注册")
    public Result addUserLogin(@RequestBody User user, HttpServletRequest request){
        String captcha = request.getHeader("captcha");
        return userLoginService.addUserLogin(user,captcha);
    }


//    @GetMapping("/captcha")
//    @ApiOperation("获取验证码")
//    public Result captcha(){
//        return userLoginService.getCaptcha();
//    }

    @GetMapping("/captcha")
    @ApiOperation("获取验证码")
    public void getCaptcha(HttpServletResponse response){
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","No-cache");
        response.setContentType("image/jpeg");
        IdentifyCode code = new IdentifyCode();
        BufferedImage img = code.getIdentifyImg();
        userLoginService.getCaptchaImags(code.getCode());
        try {
            ImageIO.write(img,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
